package cn.alise.controller.generator;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.alise.controller.common.BaseController;
import cn.alise.qdp.mapper.generator.GeneratorMapper;
import cn.alise.qdp.model.generator.Generator;

/**
 * 代码自动生成控制器
 */
@Controller
@RequestMapping(value = "/generator")
public class GeneratorController extends BaseController {
	
	private static final long serialVersionUID = 8067293756668444590L;
	
	@Autowired
	private GeneratorMapper generatorMapper;

	/**
	 * 跳转到自动创建页面
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String export(HttpServletRequest request, Model model) {
		
		return "pages/common/generator";
	}
	
	/**
	 * 执行自动生成
	 */
	@RequestMapping(value = "/execute", method = RequestMethod.POST)
	public String execute(HttpServletRequest request, Model model, RedirectAttributes attr) throws Exception {
		
		String tableNameStr = request.getParameter("tableName");
		String path = request.getParameter("path");
		
		// 拆分tableName
		String[] tableNameArr = tableNameStr.split(",");
		
		// 创建文件夹
		File file = new File(path);
		if (!file.exists()) {
			file.mkdir();
		}
		
		// 循环table
		for (int i=0; i<tableNameArr.length; i++) {
			
			// 根据tableName获取table属性信息
			Generator gt = new Generator();
			gt.setTableName(tableNameArr[i]);
			
			List<Generator> list = this.generatorMapper.getTableInfo(gt);
			
			// 1:生成model文件
			this.parseModel(list, tableNameArr[i], path);
			
			// 2:生成xml文件
			this.parseXml(list, tableNameArr[i], path);
			
			// 3:生成mapper文件
			this.parseMapper(list, tableNameArr[i], path);
			
			// 4:生成service文件
			this.parseService(list, tableNameArr[i], path);
			
			model.addAttribute("list", list);
		}
		
		model.addAttribute("_error", "代码生成成功！");
		model.addAttribute("tableName", tableNameStr);
		model.addAttribute("path", path);
		
		return "pages/common/generator";
	}
	
	/**
	 * 执行自动生成JSP
	 */
	@RequestMapping(value = "/executeJsp", method = RequestMethod.POST)
	public String executeJsp(HttpServletRequest request, Model model, RedirectAttributes attr) throws Exception {
		
		String queryStr = request.getParameter("queryStr");
		String conditionStr = request.getParameter("conditionStr");
		String insertStr = request.getParameter("insertStr");
		String updateStr = request.getParameter("updateStr");
		String requireStr = request.getParameter("requireStr");
		boolean ifDelete = Boolean.parseBoolean(request.getParameter("ifDelete"));
		String lengthStr = request.getParameter("lengthStr");
		String ifKeyStr = request.getParameter("ifKeyStr");
		String tableName = request.getParameter("tableName2");
		String path = request.getParameter("path2");
		
		// 获取tableCommont
		Generator generator = new Generator();
		generator.setTableName(tableName);
		generator = this.generatorMapper.getTableCommont(generator);
		String tableComment = generator.getTableName().replace("表", "");
		
		StringBuffer sb = new StringBuffer();
		
		// 生成jsp-list
		sb = this.processList(sb, queryStr, conditionStr, lengthStr, tableName, tableComment, requireStr, insertStr, updateStr, ifDelete, path, ifKeyStr);
		
		// 生成jsp-new
		if (!StringUtils.isEmpty(insertStr)) {
			sb = this.processInsert(sb, queryStr, conditionStr, lengthStr, tableName, tableComment, requireStr, insertStr, updateStr, ifDelete, path, ifKeyStr);
		}
		
		// 生成jsp-edit
		if (!StringUtils.isEmpty(updateStr)) {
			sb = this.processUpdate(sb, queryStr, conditionStr, lengthStr, tableName, tableComment, requireStr, insertStr, updateStr, ifDelete, path, ifKeyStr);
		}
		
		// 生成jsp删除功能
		if (ifDelete) {
			sb = this.processDelete(sb, queryStr, conditionStr, lengthStr, tableName, tableComment, requireStr, insertStr, updateStr, ifDelete, path, ifKeyStr);
		}
		
		// 生成Controller
		try (FileWriter fw = new FileWriter(path + initcap(tableName) + "Controller.java");
        	PrintWriter pw = new PrintWriter(fw)) {
        	pw.println(sb.toString());
            pw.flush();
        } catch (Exception e) {
        	logger.error(e.getMessage());
			throw e;
        }
		
		model.addAttribute("_error", "JSP生成成功！");
		
		return "pages/common/generator";
	}
	
    /**
	 * 生成Model
	 * @param list
	 * @throws Exception
	 */
	private void parseModel(List<Generator> list, String tableName, String path) throws Exception {
		
		//FileWriter fw = null;
       // PrintWriter pw = null;
		try {
			StringBuffer sb = new StringBuffer();
			
			// 引入头
			sb.append("package cn.alise.qdp.model." + initSecCap(tableName) + ";\r\n\r\n");
			
			// 注释部分
	        sb.append("/**\r\n");
	        sb.append(" * " + initSecCap(tableName) + " 实体类\r\n");
	        sb.append(" * "+new Date()+"  CHENH\r\n");
	        sb.append(" */ \r\n");
	        // 实体部分
	        sb.append("public class " + initcap(tableName) + " {\r\n\r\n");
			
	        // 属性部分
	        processAllAttrs(sb, list);
	        
	        // get、set方法
	        processAllMethod(sb, list);
	        
	        sb.append("}\r\n");
	        
	        try(FileWriter fw = new FileWriter(path + initcap(tableName) + ".java");
	        		PrintWriter  pw = new PrintWriter(fw);	){
	            pw.println(sb.toString());
	            pw.flush();
	        }catch (Exception e) {
	        	logger.error(e.getMessage());
				throw e;
			}
            
		} catch (Exception e) {
			logger.error("自动生成model类失败！");
			throw e;
		} 
		
	}
	
	/**
	 * 生成Xml
	 * @param list
	 * @throws Exception
	 */
	private void parseXml(List<Generator> list, String tableName, String path) throws Exception {
		
		//FileWriter fw = null;
        //PrintWriter pw = null;
		try {
			StringBuffer sb = new StringBuffer();
			
	        // 头部分
	        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n");
	        sb.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >\r\n");
	        sb.append("<mapper namespace=\"cn.alise.qdp.mapper." + initSecCap(tableName) + "." + initcap(tableName) + "Mapper\">\r\n\r\n");
			
	        // 方法部分
	        sb = this.processXmlMethod(sb, list, tableName);
	        sb.append("</mapper>");
	        try(FileWriter fw = new FileWriter(path + initcap(tableName) + "Mapper.xml");
	        		PrintWriter pw = new PrintWriter(fw)){
	        	  pw.println(sb.toString());
	              pw.flush();
	        }catch(Exception e){
	        	logger.error(e.getMessage());
	        	throw e;
	        }
            
		} catch (Exception e) {
			logger.error("自动生成xml类失败！");
			throw e;
		} 
		
	}
	
	/**
	 * 生成Mapper
	 * @param list
	 * @throws Exception
	 */
	private void parseMapper(List<Generator> list, String tableName, String path) throws Exception {
		
		//FileWriter fw = null;
        //PrintWriter pw = null;
		try {
			StringBuffer sb = new StringBuffer();
			
			// 引入头
			sb.append("package cn.alise.qdp.mapper." + initSecCap(tableName) + ";\r\n\r\n");
			
			// import
			sb.append("import java.util.Map;\r\n");
			sb.append("import java.util.List;\r\n");
			sb.append("import org.apache.ibatis.annotations.Mapper;\r\n");
			sb.append("import cn.alise.qdp.model." + initSecCap(tableName) + "." + initcap(tableName) + ";\r\n\r\n");
			
			// 注释部分
	        sb.append("/**\r\n");
	        sb.append(" * " + initcap(tableName) + "Mapper\r\n");
	        sb.append(" * "+new Date()+"  CHENH\r\n");
	        sb.append(" */ \r\n");
	        sb.append("@Mapper\r\n");
	        // 头
	        sb.append("public interface " + initcap(tableName) + "Mapper {\r\n\r\n");
			// 方法体
	        sb.append("\t/**\r\n");
	        sb.append("\t * 获取指定一条数据\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic List<" + initcap(tableName) + "> gets(Map<String, Object> args);\r\n\r\n");
	        sb.append("\t/**\r\n");
	        sb.append("\t * 获取列表\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic List<" + initcap(tableName) + "> list(" + initcap(tableName) + " args);\r\n\r\n");
	        sb.append("\t/**\r\n");
	        sb.append("\t * 分页列表\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic List<" + initcap(tableName) + "> page(Map<String, Object> args);\r\n\r\n");
	        sb.append("\t/**\r\n");
	        sb.append("\t * 列表总数\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic int total(" + initcap(tableName) + " args);\r\n\r\n");
	        sb.append("\t/**\r\n");
	        sb.append("\t * 删除数据\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic int delete(" + initcap(tableName) + " args);\r\n\r\n");
	        sb.append("\t/**\r\n");
	        sb.append("\t * 更新数据\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic int update(" + initcap(tableName) + " args);\r\n\r\n");
	        sb.append("\t/**\r\n");
	        sb.append("\t * 新增数据\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic int insert(" + initcap(tableName) + " args);\r\n\r\n");
	        
	        sb.append("}\r\n");
	        try(FileWriter fw = new FileWriter(path + initcap(tableName) + "Mapper.java");
	        		PrintWriter  pw = new PrintWriter(fw)){
	        	pw.println(sb.toString());
	            pw.flush();
	        }catch(Exception e){
	        	
	        	logger.error(e.getMessage());
				throw e;
	        }
	       
            
            
		} catch (Exception e) {
			logger.error("自动生成Mapper类失败！");
			throw e;
		} 
		
	}
	
	/**
	 * 生成Service
	 * @param list
	 * @throws Exception
	 */
	private void parseService(List<Generator> list, String tableName, String path) throws Exception {
		
		//FileWriter fw = null;
       // PrintWriter pw = null;
		try {
			StringBuffer sb = new StringBuffer();
			
			// 引入头
			sb.append("package cn.alise.qdp.service." + initSecCap(tableName) + ";\r\n\r\n");
			
			// import
			sb.append("import java.util.List;\r\n");
			sb.append("import java.util.Map;\r\n");
			sb.append("import javax.annotation.Resource;\r\n");
			sb.append("import org.springframework.stereotype.Service;\r\n");
			sb.append("import org.springframework.transaction.annotation.Transactional;\r\n");
			sb.append("import org.springframework.util.CollectionUtils;\r\n");
			sb.append("import cn.alise.qdp.model." + initSecCap(tableName) + "." + initcap(tableName) + ";\r\n");
			sb.append("import cn.alise.qdp.mapper." + initSecCap(tableName) + "." + initcap(tableName) + "Mapper;\r\n\r\n");
			
			// 注释部分
	        sb.append("/**\r\n");
	        sb.append(" * " + initcap(tableName) + "Service\r\n");
	        sb.append(" * "+new Date()+"  CHENH\r\n");
	        sb.append(" */ \r\n");
	        // 头
	        sb.append("@Service\r\n");
	        sb.append("@Transactional(rollbackFor = Exception.class)\r\n");
	        sb.append("public class " + initcap(tableName) + "Service {\r\n\r\n");
	        sb.append("\t@Resource(name = \"" + initSecCap(tableName) + "Mapper\")\r\n");
	        sb.append("\tprivate " + initcap(tableName) + "Mapper " + initSecCap(tableName) + "Mapper;\r\n\r\n");
			// 方法体
	        sb.append("\t/**\r\n");
	        sb.append("\t * 获取指定一条数据\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic " + initcap(tableName) + " get(" + initcap(tableName) + " args) {\r\n");
	        sb.append("\t\tList<" + initcap(tableName) + "> list = this.list(args);\r\n");
	        sb.append("\t\tif (!CollectionUtils.isEmpty(list)) {\r\n");
	        sb.append("\t\t\treturn list.get(0);\r\n");
	        sb.append("\t\t}\r\n\r\n");
	        sb.append("\t\treturn null;\r\n");
	        sb.append("\t}\r\n\r\n");
	        
	        sb.append("\t/**\r\n");
	        sb.append("\t * 获取列表\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic List<" + initcap(tableName) + "> list(" + initcap(tableName) + " args) {\r\n");
	        sb.append("\t\treturn this." + initSecCap(tableName) + "Mapper.list(args);\r\n");
	        sb.append("\t}\r\n\r\n");
	        
	        sb.append("\t/**\r\n");
	        sb.append("\t * 分页列表\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic List<" + initcap(tableName) + "> page(Map<String, Object> args) {\r\n");
	        sb.append("\t\treturn this." + initSecCap(tableName) + "Mapper.page(args);\r\n");
	        sb.append("\t}\r\n\r\n");
	        
	        sb.append("\t/**\r\n");
	        sb.append("\t * 列表总数\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic int total(" + initcap(tableName) + " args) {\r\n");
	        sb.append("\t\treturn this." + initSecCap(tableName) + "Mapper.total(args);\r\n");
	        sb.append("\t}\r\n\r\n");
	        
	        sb.append("\t/**\r\n");
	        sb.append("\t * 删除数据\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic int delete(" + initcap(tableName) + " args) {\r\n");
	        sb.append("\t\treturn this." + initSecCap(tableName) + "Mapper.delete(args);\r\n");
	        sb.append("\t}\r\n\r\n");
	        
	        sb.append("\t/**\r\n");
	        sb.append("\t * 更新数据\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic int save(" + initcap(tableName) + " args) {\r\n");
	        sb.append("\t\treturn this." + initSecCap(tableName) + "Mapper.insert(args);\r\n");
	        sb.append("\t}\r\n\r\n");
	        
	        sb.append("\t/**\r\n");
	        sb.append("\t * 新增数据\r\n");
	        sb.append("\t */ \r\n");
	        sb.append("\tpublic int update(" + initcap(tableName) + " args) {\r\n");
	        sb.append("\t\treturn this." + initSecCap(tableName) + "Mapper.update(args);\r\n");
	        sb.append("\t}\r\n\r\n");
	        
	        sb.append("}\r\n");
	        try(FileWriter fw = new FileWriter(path + initcap(tableName) + "Service.java");
	           PrintWriter  pw = new PrintWriter(fw);	){
	        	 pw.println(sb.toString());
	             pw.flush();
	        }catch (Exception e) {
	        	logger.error(e.getMessage());
				throw e;
			}
           
            
		} catch (Exception e) {
			logger.error("自动生成Service类失败！");
			throw e;
		} 
		
	}
	
	/**
     * 将输入字符串的首字母改成大写并改为驼峰式
     * @param str
     * @return
     */
    private String initcap(String str) {
    	
        char[] ch = str.toCharArray();
    	
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char)(ch[0] - 32);
        }
        
        for (int i=0; i<10; i++) {
        	if (str.contains("_")) {
            	ch[str.indexOf("_") + 1] = (char)(ch[str.indexOf("_") + 1] - 32);
            }
        	str = new String(ch);
        	str = str.replaceFirst("_", "");
        	ch = str.toCharArray();
        }
        
        str = new String(ch);
        str = str.replace("_", "");
        
        return str;
    }
    
    /**
     * 全部改为大写
     * @param str
     * @return
     */
    private String initAllcap(String str) {
    	
        str = str.toUpperCase();
        
        return str;
    }
    
    /**
     * 将_后的首字母大写并去掉_
     * @param str
     * @return
     */
    private String initSecCap(String str) {
    	
    	char[] ch = str.toCharArray();
    	
    	for (int i=0; i<10; i++) {
    		if (str.contains("_")) {
            	ch[str.indexOf("_") + 1] = (char)(ch[str.indexOf("_") + 1] - 32);
            }
        	str = new String(ch);
        	str = str.replaceFirst("_", "");
        	ch = str.toCharArray();
        }
    	
    	str = new String(ch);
        str = str.replace("_", "");
        
        return str;
    }
    
    /**
     * 先全部小写后将_后的首字母大写并去掉_
     * @param str
     * @return
     */
    private String initSecCapLow(String str) {
    	
    	str = str.toLowerCase();
    	char[] ch = str.toCharArray();
    	
    	for (int i=0; i<10; i++) {
    		if (str.contains("_")) {
            	ch[str.indexOf("_") + 1] = (char)(ch[str.indexOf("_") + 1] - 32);
            }
        	str = new String(ch);
        	str = str.replaceFirst("_", "");
        	ch = str.toCharArray();
        }
    	
    	str = new String(ch);
        str = str.replace("_", "");
        
        return str;
    }
    
    /**
     * 先全部小写后将输入字符串的首字母改成大写并改为驼峰式
     * @param str
     * @return
     */
    @SuppressWarnings("unused")
	private String initcapLow(String str) {
    	
    	str = str.toLowerCase();
        char[] ch = str.toCharArray();
    	
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char)(ch[0] - 32);
        }
        
        for (int i=0; i<10; i++) {
        	if (str.contains("_")) {
            	ch[str.indexOf("_") + 1] = (char)(ch[str.indexOf("_") + 1] - 32);
            }
        	str = new String(ch);
        	str = str.replaceFirst("_", "");
        	ch = str.toCharArray();
        }
        
        str = new String(ch);
        str = str.replace("_", "");
        
        return str;
    }
    
    /**
     * 1、若为car_status,先全部小写后将_后的首字母大写并去掉_
     * 2、若为carStatus,则直接返回
     * @param str
     * @return
     */
    private String initCapLowBy2(String str) {
    	
    	if (str.indexOf("_") < 0) {
    		return str;
    	} else {
    		str = str.toLowerCase();
        	char[] ch = str.toCharArray();
        	
        	for (int i=0; i<10; i++) {
        		if (str.contains("_")) {
                	ch[str.indexOf("_") + 1] = (char)(ch[str.indexOf("_") + 1] - 32);
                }
            	str = new String(ch);
            	str = str.replaceFirst("_", "");
            	ch = str.toCharArray();
            }
        	
        	str = new String(ch);
            str = str.replace("_", "");
            
            return str;
    	}
    }
    
    /**
     * 获得列的数据类型
     * @param sqlType
     * @return
     */
    private String sqlType2JavaType(String sqlType) {
         
        if (sqlType.equalsIgnoreCase("bit")) {
            return "boolean";
        } else if (sqlType.equalsIgnoreCase("tinyint")) {
            return "byte";
        } else if(sqlType.equalsIgnoreCase("smallint")) {
            return "Integer";
        } else if(sqlType.equalsIgnoreCase("int")) {
            return "Integer";
        } else if(sqlType.equalsIgnoreCase("bigint")) {
            return "Long";
        } else if(sqlType.equalsIgnoreCase("float")) {
            return "Float";
        } else if(sqlType.equalsIgnoreCase("numeric") 
                || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money") 
                || sqlType.equalsIgnoreCase("smallmoney") || sqlType.equalsIgnoreCase("double")) {
            return "Double";
        } else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char") 
                || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar") 
                || sqlType.equalsIgnoreCase("text")) {
            return "String";
        } else if(sqlType.equalsIgnoreCase("datetime")) {
            return "Date";
        } else if(sqlType.equalsIgnoreCase("image")) {
            return "Blod";
        } else if(sqlType.equalsIgnoreCase("timestamp")) {
            return "Timestamp";
        } else if(sqlType.equalsIgnoreCase("decimal")) {
            return "BigDecimal";
        }
         
        return null;
    }
    
    /**
     * 生成所有属性
     * @param sb
     */
    private void processAllAttrs(StringBuffer sb, List<Generator> list) {
         
        for (int i=0; i<list.size(); i++) {
        	sb.append("\t/**\r\n");
	        sb.append("\t * " + list.get(i).getColComment() + "\r\n");
	        sb.append("\t */ \r\n");
            sb.append("\tprivate " + sqlType2JavaType(list.get(i).getColType()) + " " + initCapLowBy2(list.get(i).getColName()) + ";\r\n\r\n");
        }
         
    }
    
    /**
     * 生成所有方法
     * @param sb
     */
    private void processAllMethod(StringBuffer sb, List<Generator> list) {
         
        for (int i=0; i<list.size(); i++) {
            sb.append("\tpublic void set" + initcap(list.get(i).getColName()) + "(" + sqlType2JavaType(list.get(i).getColType()) + " " + initCapLowBy2(list.get(i).getColName()) + ") {\r\n");
            sb.append("\t\tthis." + initCapLowBy2(list.get(i).getColName()) + "=" + initCapLowBy2(list.get(i).getColName()) + ";\r\n");
            sb.append("\t}\r\n\r\n");
            sb.append("\tpublic " + sqlType2JavaType(list.get(i).getColType()) + " get" + initcap(list.get(i).getColName()) + "() {\r\n");
            sb.append("\t\treturn " + initCapLowBy2(list.get(i).getColName()) + ";\r\n");
            sb.append("\t}\r\n\r\n");
        }
         
    }
    
    /**
     * xml生成所有方法
     * @param sb
     */
    private StringBuffer processXmlMethod(StringBuffer sb, List<Generator> list, String tableName) {
        
    	// 首先循环list获得所有字段串、where条件串
    	String colStr = "";
    	StringBuffer selectWhereStr = new StringBuffer();
    	StringBuffer updateWhereStr = new StringBuffer();
    	StringBuffer insertWhereStr1 = new StringBuffer();
    	StringBuffer insertWhereStr2 = new StringBuffer();
    	
        for (int i=0; i<list.size(); i++) {
        	if (i + 1 >= list.size()) {
        		colStr += list.get(i).getColName() + " as " + initCapLowBy2(list.get(i).getColName());
        	} else {
        		colStr += list.get(i).getColName() + " as " + initCapLowBy2(list.get(i).getColName()) + ",";
        	}
        	//拼凑selectWhereStr
        	selectWhereStr.append("\t\t<if test=\"" + initCapLowBy2(list.get(i).getColName()) + " != null and " + initCapLowBy2(list.get(i).getColName()) + " != ''\">\r\n");
        	selectWhereStr.append("\t\t\tand " + list.get(i).getColName() + " = #{" + initCapLowBy2(list.get(i).getColName()) + "}\r\n");
        	selectWhereStr.append("\t\t</if>\r\n");
        	
        	if (i != 0) {
        		//拼凑updateWhereStr
        		updateWhereStr.append("\t\t\t<if test=\"" + initCapLowBy2(list.get(i).getColName()) + " != null\">" + list.get(i).getColName() + " = #{" + initCapLowBy2(list.get(i).getColName()) + "},</if>\r\n");
        		//拼凑insertWhereStr1
            	insertWhereStr1.append("\t\t\t<if test=\"" + initCapLowBy2(list.get(i).getColName()) + " != null\">" + list.get(i).getColName() + ",</if>\r\n");
            	//拼凑insertWhereStr2
            	insertWhereStr2.append("\t\t\t<if test=\"" + initCapLowBy2(list.get(i).getColName()) + " != null\">#{" + initCapLowBy2(list.get(i).getColName()) + "},</if>\r\n");
        	}
        	
        }
        
        // 拼凑list方法
        sb.append("\t<select id=\"list\" parameterType=\"cn.alise.qdp.model." + initSecCap(tableName) + "."+ initcap(tableName) +"\" "
        		+ "resultType=\"cn.alise.qdp.model." + initSecCap(tableName) + "."+ initcap(tableName) +"\">\r\n");
        sb.append("\t\tselect " + colStr + "\r\n");
        sb.append("\t\t  from " + initAllcap(tableName) + "\r\n");
        sb.append("\t\t where 1 = 1\r\n");
        sb.append(selectWhereStr + "\r\n");
        sb.append("\t</select>\r\n\r\n");
        
        // 拼凑page方法
        sb.append("\t<select id=\"page\" parameterType=\"map\" resultType=\"cn.alise.qdp.model." + initSecCap(tableName) + "."+ initcap(tableName) +"\">\r\n");
        sb.append("\t\tselect " + colStr + "\r\n");
        sb.append("\t\t  from " + initAllcap(tableName) + "\r\n");
        sb.append("\t\t where 1 = 1\r\n");
        sb.append(selectWhereStr + "\r\n");
        sb.append("\t\t limit #{start}, #{size} \r\n");
        sb.append("\t</select> \r\n\r\n");
        
        // 拼凑total方法
        sb.append("\t<select id=\"total\" parameterType=\"cn.alise.qdp.model." + initSecCap(tableName) + "."+ initcap(tableName) +"\" resultType=\"int\">\r\n");
        sb.append("\t\tselect count(1) \r\n");
        sb.append("\t\t  from " + initAllcap(tableName) + "\r\n");
        sb.append("\t\t where 1 = 1\r\n");
        sb.append(selectWhereStr + "\r\n");
        sb.append("\t</select> \r\n\r\n");
        
        // 拼凑delete方法
        sb.append("\t<delete id=\"delete\" parameterType=\"cn.alise.qdp.model." + initSecCap(tableName) + "."+ initcap(tableName) +"\">\r\n");
        sb.append("\t\tdelete from " + initAllcap(tableName) + " \r\n");
        sb.append("\t\t where 1 = 1\r\n");
        sb.append(selectWhereStr + "\r\n");
        sb.append("\t</delete> \r\n\r\n");
        
        // 拼凑update方法
        sb.append("\t<update id=\"update\" parameterType=\"cn.alise.qdp.model." + initSecCap(tableName) + "."+ initcap(tableName) +"\">\r\n");
        sb.append("\t\tupdate " + initAllcap(tableName) + " \r\n");
        sb.append("\t\t<set>\r\n");
        sb.append(updateWhereStr + "");
        sb.append("\t\t</set>\r\n");
        sb.append("\t\twhere " + list.get(0).getColName() + " = #{" + initCapLowBy2(list.get(0).getColName()) + "}\r\n");
        sb.append("\t</update> \r\n\r\n");
        
        // 拼凑insert方法
        sb.append("\t<insert id=\"insert\" keyProperty=\"" + list.get(0).getColName() + "\" useGeneratedKeys=\"true\" parameterType=\"cn.alise.qdp.model." + initSecCap(tableName) + "."+ initcap(tableName) +"\">\r\n");
        sb.append("\t\tinsert into " + initAllcap(tableName) + "\r\n");
        sb.append("\t\t<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">\r\n");
        sb.append(insertWhereStr1 + "");
        sb.append("\t\t</trim>\r\n");
        sb.append("\t\t<trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\" >\r\n");
        sb.append(insertWhereStr2 + "");
        sb.append("\t\t</trim>\r\n");
        sb.append("\t</insert> \r\n\r\n");
        
        return sb;
    }
    
    /**
     * 生成查询功能
     * @param sb
     */
    private StringBuffer processList(StringBuffer sb, String queryStr, String conditionStr, String lengthStr, String tableName, String tableComment, String requireStr, String insertStr, String updateStr, boolean ifDelete, String path, String ifKeyStr) {
        // 拼凑controller
    	sb.append("package cn.alise.controller." + initSecCap(tableName) + ";\r\n\r\n");
    	sb.append("import java.util.HashMap;\r\n");
    	sb.append("import java.util.List;\r\n");
    	sb.append("import java.util.Collections;\r\n");
    	sb.append("import javax.servlet.http.HttpServletRequest;\r\n");
    	sb.append("import javax.servlet.http.HttpServletResponse;\r\n");
    	sb.append("import org.springframework.beans.factory.annotation.Autowired;\r\n");
    	sb.append("import org.springframework.stereotype.Controller;\r\n");
    	sb.append("import org.springframework.ui.Model;\r\n");
    	sb.append("import org.springframework.util.CollectionUtils;\r\n");
    	sb.append("import cn.alise.util.JsonUtil;\r\n");
    	sb.append("import com.alibaba.fastjson.JSONArray;\r\n");
    	sb.append("import cn.alise.util.JSONResult;\r\n");
    	sb.append("import org.springframework.web.bind.annotation.RequestMapping;\r\n");
    	sb.append("import org.springframework.web.bind.annotation.RequestMethod;\r\n");
    	sb.append("import org.springframework.web.servlet.mvc.support.RedirectAttributes;\r\n");
    	sb.append("import cn.alise.qdp.model.common.Pagination;\r\n");
    	sb.append("import cn.alise.qdp.model." + initSecCap(tableName) + "." + initcap(tableName) + ";\r\n");
    	sb.append("import cn.alise.qdp.service." + initSecCap(tableName) + "." + initcap(tableName) + "Service;\r\n");
    	sb.append("import cn.alise.controller.common.BaseController;\r\n\r\n");
    	
    	// 注释部分
        sb.append("/**\r\n");
        sb.append(" * " + tableComment + "控制器\r\n");
        sb.append(" * "+new Date()+"  CHENH\r\n");
        sb.append(" */ \r\n");
        
        // 头
        sb.append("@Controller\r\n");
        sb.append("@RequestMapping(value = \"/" + initSecCap(tableName) + "\")\r\n");
        sb.append("public class " + initcap(tableName) + "Controller extends BaseController {\r\n\r\n");
        sb.append("\tprivate static final long serialVersionUID = 1L;\r\n\r\n");
        sb.append("\tprivate static final String ERROR_TITLE = \"_error\";\r\n");
        sb.append("\tprivate static final String REDIRECT_LIST = \"redirect:list\";\r\n\r\n");
        sb.append("\t@Autowired\r\n");
        sb.append("\tprivate " + initcap(tableName) + "Service " + initSecCap(tableName) + "Service;\r\n\r\n");
        
        // 列表方法
        sb.append("\t/**\r\n");
        sb.append("\t * 获取列表\r\n");
        sb.append("\t */\r\n");
        sb.append("\t@RequestMapping(value = \"/list\")\r\n");
        sb.append("\tpublic String list(HttpServletRequest request, Model model, " + initcap(tableName) + " args, Pagination page) {\r\n\r\n");
        sb.append("\t\tHashMap<String, Object> params = new HashMap<String, Object>();\r\n\r\n");
        sb.append("\t\t// 查询总行数\r\n");
        sb.append("\t\tint total = this." + initSecCap(tableName) + "Service.total(args);\r\n");
        sb.append("\t\tif (total > 0) {\r\n\r\n");
        sb.append("\t\t\tpage.setTotalCount(total);\r\n");
     
        sb.append("\t\t\tparams.put(\"pageSize\",    String.valueOf(page.getRowsPerPage()));\r\n");
        sb.append("\t\t\tparams.put(\"currentPage\", String.valueOf(page.getCurrentPage()));\r\n\r\n");
        sb.append("\t\t\t// 设置分页信息\r\n");
        sb.append("\t\t\tparams.put(\"start\", (page.getCurrentPage() - 1) * page.getRowsPerPage());\r\n");
        sb.append("\t\t\tparams.put(\"size\",  page.getRowsPerPage());\r\n\r\n");
        
        sb.append("\t\t\t//查询条件\r\n");
        
        String conditionStrArr[] = null;
        if (!StringUtils.isEmpty(conditionStr.trim())) {
        	
        	conditionStrArr = conditionStr.trim().split("@");
        	
        	for (int i=0; i<conditionStrArr.length; i++) {
        		String arr[] = conditionStrArr[i].split("#");
        		String colName = arr[0];
        		
        		if (!StringUtils.isEmpty(colName)) {
        			sb.append("\t\t\tparams.put(\"" + initCapLowBy2(colName) + "\",     args.get" + initcap(colName) + "());\r\n");
        		}
        	}
        }
        
        sb.append("\r\n\r\n");
        sb.append("\t\t\tList<" + initcap(tableName) + "> list = this." + initSecCap(tableName) + "Service.page(params);\r\n");
        sb.append("\t\t\tif (!CollectionUtils.isEmpty(list)) {\r\n");
        sb.append("\t\t\t\tmodel.addAttribute(\"list\", list);\r\n");
        sb.append("\t\t\t} else {\r\n");
        sb.append("\t\t\t\tmodel.addAttribute(\"list\", Collections.EMPTY_LIST);\r\n");
        sb.append("\t\t\t}\r\n");
        sb.append("\t\t}\r\n\r\n");
        sb.append("\t\tmodel.addAttribute(\"" + initSecCap(tableName) + "\", args);\r\n");
        sb.append("\t\tmodel.addAttribute(\"pagination\", page);\r\n\r\n");
        sb.append("\t\treturn \"pages/" + initSecCap(tableName) + "/" + initSecCap(tableName) + "-list\";\r\n");
        sb.append("\t}\r\n");
        
        if (StringUtils.isEmpty(insertStr) && StringUtils.isEmpty(updateStr) && ifDelete == false) {
        	sb.append("}\r\n\r\n");
        }
    	
    	// 生成JSP-list
        StringBuffer sbJsp = new StringBuffer();
        sbJsp.append("<%@ page language=\"java\" contentType=\"text/html; charset=utf-8\" pageEncoding=\"utf-8\"%>\r\n");
        sbJsp.append("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%>\r\n");
        sbJsp.append("<%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jsp/jstl/fmt\"%>\r\n");
        sbJsp.append("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %>\r\n");
        sbJsp.append("<jsp:include page=\"../common/file.jsp\" />\r\n");
        sbJsp.append("<head>\r\n");
        sbJsp.append("</head>\r\n");
        sbJsp.append("<body>\r\n");
        sbJsp.append("\t<script type=\"text/javascript\">\r\n");
        sbJsp.append("\t\t//初始化滚动条\r\n");
        sbJsp.append("\t\t$(\"html\").niceScroll({cursorcolor:\"#000000\",zindex:999999,bouncescroll:true,cursoropacitymax:0.4,cursorborder:\"\",cursorborderradius:7,cursorwidth:\"7px\",background:\"rgba(0,0,0,.1)\",autohidemode:true,railpadding:{top:0,right:2,left:2,bottom:0}});\r\n");
        sbJsp.append("\t\t//页面信息提示\r\n");
        sbJsp.append("\t\tvar returnMsg = \"${_error}\";\r\n");
        sbJsp.append("\t\tvar authoriMsg = \"${_authoriError}\";\r\n");
        sbJsp.append("\t</script>\r\n");
        sbJsp.append("\t<div id=\"title-breadcrumb-option-demo\" class=\"page-title-breadcrumb\">\r\n");
        sbJsp.append("\t\t<ol class=\"breadcrumb page-breadcrumb pull-left\">\r\n");
        sbJsp.append("\t\t\t<li><i class=\"fa fa-home\"></i>&nbsp;<a href=\"${pageContext.request.contextPath}/" + initSecCap(tableName) + "/list\">" + tableComment + "管理</a>&nbsp;&nbsp;<i class=\"fa fa-angle-right\"></i>&nbsp;</li>\r\n");
        sbJsp.append("\t\t\t<li class=\"active\">" + tableComment + "总览</li>\r\n");
        sbJsp.append("\t\t</ol>\r\n");
        sbJsp.append("\t</div>\r\n");
        sbJsp.append("\t<div style=\"clear: both\"></div>\r\n");
        sbJsp.append("\t<div class=\"main-right-content\">\r\n");
        sbJsp.append("\t\t<div class=\"main-right-div\">\r\n");
        sbJsp.append("\t\t\t<div class=\"main-right-query-div\">\r\n");
        sbJsp.append("\t\t\t\t<form id=\"query-form-1\" action=\"${pageContext.request.contextPath}/" + initSecCap(tableName) + "/list\" method=\"post\">\r\n");
        sbJsp.append("\t\t\t\t\t<div class=\"main-right-search row\">\r\n");
        
        if (!StringUtils.isEmpty(conditionStr.trim()) && conditionStrArr.length > 0) {
        	for (int i=0; i<conditionStrArr.length; i++) {
        		String arr[] = conditionStrArr[i].split("#");
        		String colName = arr[0];
        		String colCommont = arr[1];
        		
        		if (!StringUtils.isEmpty(colName)) {
        			sbJsp.append("\t\t\t\t\t\t<div class=\"col-lg-2\">\r\n");
        			sbJsp.append("\t\t\t\t\t\t"+colCommont+": <input type=\"text\" id=\"" + initCapLowBy2(colName) + "\" name=\"" + initCapLowBy2(colName) + "\" value=\"<c:out value='${" + initSecCap(tableName) + "." + initCapLowBy2(colName) + "}'/>\" placeholder=\"请输入"+colCommont+"\" onkeyup=\"this.value=this.value.replace(/ /g,'')\"");
        			this.checkLength(sbJsp, lengthStr, colName);
        			sbJsp.append("/>\r\n");
        			sbJsp.append("\t\t\t\t\t\t</div>\r\n");
        		}
        	}
        }
        
        sbJsp.append("\t\t\t\t\t\t<div class=\"col-lg-2\">\r\n");
        sbJsp.append("\t\t\t\t\t\t\t&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\r\n");
        sbJsp.append("\t\t\t\t\t\t\t<button type=\"button\" class=\"btn btn-blue btn-query\">查 询</button>\r\n");
        sbJsp.append("\t\t\t\t\t\t\t<button type=\"button\" class=\"btn btn-gray btn-rest\">重 置</button>\r\n");
        if (!StringUtils.isEmpty(insertStr)) {
        	sbJsp.append("\t\t\t\t\t\t\t<button type=\"button\" class=\"btn btn-red btn-add\">新 增</button>\r\n");
        }
        sbJsp.append("\t\t\t\t\t\t</div>\r\n");
        sbJsp.append("\t\t\t\t\t</div>\r\n");
        sbJsp.append("\t\t\t\t</form>\r\n");
        sbJsp.append("\t\t\t</div>\r\n");
        sbJsp.append("\t\t\t<div style=\"clear: both;\"></div>\r\n");
        sbJsp.append("\t\t\t<div class=\"main-right-table-div\">\r\n");
        sbJsp.append("\t\t\t\t<table class=\"main-right-table\">\r\n");
        sbJsp.append("\t\t\t\t\t<!--\r\n");
        sbJsp.append("\t\t\t\t\t<colgroup>\r\n");
        
        String queryStrArr[] = null;
        if (!StringUtils.isEmpty(queryStr.trim())) {
        	queryStrArr = queryStr.trim().split("@");
        	for (int i=0; i<queryStrArr.length; i++) {
    			sbJsp.append("\t\t\t\t\t\t<col style=\"width: 10%;\">\r\n");
        	}
        }
        if (ifDelete || !StringUtils.isEmpty(updateStr)) {
        	sbJsp.append("\t\t\t\t\t\t<col style=\"width: 10%;\">\r\n");
        }
        sbJsp.append("\t\t\t\t\t</colgroup>\r\n");
        sbJsp.append("\t\t\t\t\t -->\r\n");
        sbJsp.append("\t\t\t\t\t<thead>\r\n");
        sbJsp.append("\t\t\t\t\t\t<tr>\r\n");
        
        if (!StringUtils.isEmpty(queryStr.trim()) && queryStrArr.length > 0) {
        	for (int i=0; i<queryStrArr.length; i++) {
        		String arr[] = queryStrArr[i].split("#");
        		String colCommont = arr[1];
        		
        		sbJsp.append("\t\t\t\t\t\t\t<td>"+colCommont+"</td>\r\n");
        	}
        }
        if (ifDelete || !StringUtils.isEmpty(updateStr)) {
        	sbJsp.append("\t\t\t\t\t\t\t<td>操作</td>\r\n");
        }
        sbJsp.append("\t\t\t\t\t\t</tr>\r\n");
        sbJsp.append("\t\t\t\t\t</thead>\r\n");
        sbJsp.append("\t\t\t\t\t<tbody>\r\n");
        sbJsp.append("\t\t\t\t\t\t<c:if test=\"${list != null && list.size() > 0}\">\r\n");
        sbJsp.append("\t\t\t\t\t\t\t<c:forEach items=\"${list}\" var=\"d\" varStatus=\"st\">\r\n");
        sbJsp.append("\t\t\t\t\t\t\t\t<tr>\r\n");
        if (!StringUtils.isEmpty(queryStr.trim()) && queryStrArr.length > 0) {
        	for (int i=0; i<queryStrArr.length; i++) {
        		String arr[] = queryStrArr[i].split("#");
        		String colName = arr[0];
        		
        		sbJsp.append("\t\t\t\t\t\t\t\t\t<td style=\"text-align: center;\"><span>${d." + initCapLowBy2(colName) + "}</span></td>\r\n");
        	}
        }
        if (ifDelete || !StringUtils.isEmpty(updateStr)) {
        	sbJsp.append("\t\t\t\t\t\t\t\t\t<td style=\"text-align: center;\">\r\n");
        	if (!StringUtils.isEmpty(updateStr)) {
        		sbJsp.append("\t\t\t\t\t\t\t\t\t\t<a data-id=\"<c:out value='${d."+initCapLowBy2(ifKeyStr)+"}'/>\" class=\"stylebuttonwee stylemedium stylesquare stylegreen row-update-btn\" href=\"javascript:void(0);\">修改</a>\r\n");
        		sbJsp.append("\t\t\t\t\t\t\t\t\t\t&nbsp;\r\n");
        	}
        	if (ifDelete) {
        		sbJsp.append("\t\t\t\t\t\t\t\t\t\t<a data-id=\"<c:out value='${d."+initCapLowBy2(ifKeyStr)+"}'/>\" class=\"stylebuttonwee stylemedium stylesquare stylegrey row-del-btn\" href=\"javascript:void(0);\">删除</a>\r\n");
        	}
        }
        sbJsp.append("\t\t\t\t\t\t\t\t</tr>\r\n");
        sbJsp.append("\t\t\t\t\t\t\t</c:forEach>\r\n");
        sbJsp.append("\t\t\t\t\t\t</c:if>\r\n");
        sbJsp.append("\t\t\t\t\t\t<c:if test=\"${list == null || list.size() <= 0}\">\r\n");
        sbJsp.append("\t\t\t\t\t\t\t<tr>\r\n");
        int queryStrArrLength = queryStrArr.length;
        if (!StringUtils.isEmpty(updateStr) || ifDelete == true) {
        	queryStrArrLength = queryStrArrLength + 1;
        }
        sbJsp.append("\t\t\t\t\t\t\t\t<td colspan=\""+queryStrArrLength+"\" style=\"padding: 5px; text-align: center;\">查询无记录！</td>\r\n");
        sbJsp.append("\t\t\t\t\t\t\t</tr>\r\n");
        sbJsp.append("\t\t\t\t\t\t</c:if>\r\n");
        sbJsp.append("\t\t\t\t\t</tbody>\r\n");
        sbJsp.append("\t\t\t\t</table>\r\n");
        sbJsp.append("\t\t\t\t<%@include file=\"../common/page.jsp\" %>\r\n");
        sbJsp.append("\t\t\t</div>\r\n");
        sbJsp.append("\t\t</div>\r\n");
        sbJsp.append("\t</div>\r\n");
        sbJsp.append("\t<script type=\"text/javascript\">\r\n");
        sbJsp.append("\tvar formJsion = $(\"#query-form-1\").serializeArray();\r\n");
        sbJsp.append("\tnew Pagination({container: '.page',fm: \"#query-form-1\",formData:formJsion});\r\n");
        sbJsp.append("\t\tvar ctxt = \"${pageContext.request.contextPath}\";\r\n\r\n");
        sbJsp.append("\t\t// 查询\r\n");
        sbJsp.append("\t\t$('.btn-query').click(function() {\r\n");
        sbJsp.append("\t\t\t$('#query-form-1').submit();\r\n");
        sbJsp.append("\t\t\tformJsion = $(\"#query-form-1\").serializeArray();\r\n");
        sbJsp.append("\t\t});\r\n\r\n");
        sbJsp.append("\t\t// 重置\r\n");
        sbJsp.append("\t\t$('.btn-rest').click(function() {\r\n");
        sbJsp.append("\t\t\twindow.location.href = $('#query-form-1').attr(\"action\");\r\n");
        sbJsp.append("\t\t});\r\n\r\n");
        
        if (!StringUtils.isEmpty(insertStr)) {
        	sbJsp.append("\t\t//新增\r\n");
        	sbJsp.append("\t\t$('.btn-add').click(function() {\r\n");
        	sbJsp.append("\t\t\tart.dialog.open(ctxt + '/" + initSecCap(tableName) + "/create', {\r\n");
        	sbJsp.append("\t\t\t\ttitle: '新增"+tableComment+"',width: 420,height: 500,lock: true,opacity: 0.3\r\n");
        	sbJsp.append("\t\t\t});\r\n");
        	sbJsp.append("\t\t});\r\n\r\n");
        }
        
        if (!StringUtils.isEmpty(updateStr)) {
        	sbJsp.append("\t\t//修改\r\n");
        	sbJsp.append("\t\t$('.row-update-btn').click(function() {\r\n");
        	sbJsp.append("\t\t\tvar id = $(this).data('id');\r\n");
        	sbJsp.append("\t\t\tart.dialog.open(ctxt + '/" + initSecCap(tableName) + "/edit?"+initCapLowBy2(ifKeyStr)+"='+id, {\r\n");
        	sbJsp.append("\t\t\t\ttitle: '修改"+tableComment+"',width: 420,height: 500,lock: true,opacity: 0.3\r\n");
        	sbJsp.append("\t\t\t});\r\n");
        	sbJsp.append("\t\t});\r\n\r\n");
        }
        
        if (ifDelete) {
        	sbJsp.append("\t\t// 删除\r\n");
        	sbJsp.append("\t\t$('.row-del-btn').click(function() {\r\n");
        	sbJsp.append("\t\t\tvar id = $(this).data('id');\r\n");
        	sbJsp.append("\t\t\tart.dialog.confirm('你确定要删除该"+tableComment+"吗？', function () {\r\n");
        	sbJsp.append("\t\t\t\tart.dialog.tips('正在提交...', 0.5);\r\n");
        	sbJsp.append("\t\t\t\t$.post(ctxt + \"/" + initSecCap(tableName) + "/delete\", {\""+initCapLowBy2(ifKeyStr)+"\": id}, function(msg) {\r\n");
        	sbJsp.append("\t\t\t\t\tif (msg != undefined && msg.status == 0) {\r\n");
        	sbJsp.append("\t\t\t\t\t\tart.dialog.alert(msg.message, function() {\r\n");
        	sbJsp.append("\t\t\t\t\t\t\t$('#query-form-1').submit();\r\n");
        	sbJsp.append("\t\t\t\t\t\t});\r\n");
        	sbJsp.append("\t\t\t\t\t} else {\r\n");
        	sbJsp.append("\t\t\t\t\t\tart.dialog.tips(msg.message, 2);\r\n");
        	sbJsp.append("\t\t\t\t\t}\r\n");
        	sbJsp.append("\t\t\t\t},'json');\r\n");
        	sbJsp.append("\t\t\t}, function () {\r\n");
        	sbJsp.append("\t\t\t\tart.dialog.tips('执行已取消', 0.3);\r\n");
        	sbJsp.append("\t\t\t});\r\n");
        	sbJsp.append("\t\t});\r\n\r\n");
        }
        
        sbJsp.append("\t\t//下拉框初始化图形\r\n");
        sbJsp.append("\t\t$(\".chosen-select\").chosen({disable_search_threshold: 10});\r\n\r\n");
        sbJsp.append("\t</script>\r\n");
        sbJsp.append("</body>");
    	
        // 生成jsp-list
 		try (FileWriter fw = new FileWriter(path + initSecCap(tableName) + "-list.jsp");
 			PrintWriter pw = new PrintWriter(fw)) {
         	pw.println(sbJsp.toString());
            pw.flush();
        } catch (Exception e) {
         	logger.error(e.getMessage());
        }
        
    	return sb;
    }
    
    /**
     * 生成新增功能
     * @param sb
     */
    private StringBuffer processInsert(StringBuffer sb, String queryStr, String conditionStr, String lengthStr, String tableName, String tableComment, String requireStr, String insertStr, String updateStr, boolean ifDelete, String path, String ifKeyStr) {

    	// 新增方法
        sb.append("\t/**\r\n");
        sb.append("\t * 跳转新增页面\r\n");
        sb.append("\t */\r\n");
        sb.append("\t@RequestMapping(value = \"/create\", method = RequestMethod.GET)\r\n");
        sb.append("\tpublic String create(HttpServletRequest request, Model model) {\r\n");
        sb.append("\t\treturn \"pages/" + initSecCap(tableName) + "/" + initSecCap(tableName) + "-new\";\r\n");
        sb.append("\t}\r\n\r\n");
        
        sb.append("\t/**\r\n");
        sb.append("\t * 新增\r\n");
        sb.append("\t */\r\n");
        sb.append("\t@RequestMapping(value = \"/insert\", method = RequestMethod.POST)\r\n");
        sb.append("\tpublic String add(HttpServletRequest request, " + initcap(tableName) + " args, RedirectAttributes attr) {\r\n\r\n");
        sb.append("\t\tlogger.info(\""+tableComment+"管理新增--开始！入参：{}\", JsonUtil.toJSON(args));\r\n\r\n");
        sb.append("\t\tint row = this." + initSecCap(tableName) + "Service.save(args);\r\n\r\n");
        sb.append("\t\tif (row >= 0) {\r\n");
        sb.append("\t\t\tlogger.info(\"新增"+tableComment+"--成功！出参：{}\", JsonUtil.toJSON(row));\r\n");
        sb.append("\t\t\tattr.addFlashAttribute(ERROR_TITLE, \""+tableComment+"新增成功！\");\r\n");
        sb.append("\t\t} else {\r\n");
        sb.append("\t\t\tlogger.info(\"新增"+tableComment+"--失败！出参：{}\", JsonUtil.toJSON(row));\r\n");
        sb.append("\t\t\tattr.addFlashAttribute(ERROR_TITLE, \""+tableComment+"新增失败！\");\r\n");
        sb.append("\t\t}\r\n");
        sb.append("\t\treturn REDIRECT_LIST;\r\n");
        sb.append("\t}\r\n\r\n");
        
        if (StringUtils.isEmpty(updateStr) && ifDelete == false) {
        	sb.append("}\r\n");
        }
    	
    	// 生成JSP-new
        StringBuffer sbJsp = new StringBuffer();
        sbJsp.append("<%@ page language=\"java\" contentType=\"text/html; charset=utf-8\" pageEncoding=\"utf-8\"%>\r\n");
        sbJsp.append("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%>\r\n");
        sbJsp.append("<%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jsp/jstl/fmt\"%>\r\n");
        sbJsp.append("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %>\r\n");
        sbJsp.append("<jsp:include page=\"../common/file.jsp\" />\r\n");
        sbJsp.append("<head>\r\n");
        sbJsp.append("</head>\r\n");
        sbJsp.append("<body class=\"dialog_body\">\r\n");
        sbJsp.append("<form id=\"submit_form\" action=\"${pageContext.request.contextPath}/" + initSecCap(tableName) + "/insert\" method=\"post\" target=\"_parent\">\r\n");
        sbJsp.append("<div class=\"dialog-two-div\">\r\n");
        sbJsp.append("\t<table class=\"dialog-two-table\">\r\n");
        
        String insertStrArr[] = null;
        if (!StringUtils.isEmpty(insertStr.trim())) {
        	
        	insertStrArr = insertStr.trim().split("@");
        	
        	for (int i=0; i<insertStrArr.length; i++) {
        		String arr[] = insertStrArr[i].split("#");
        		String colName = arr[0];
        		String colCommont = arr[1];
        		
        		sbJsp.append("\t\t<tr>\r\n");
        		sbJsp.append("\t\t\t<td class=\"dialog-td-right\">"+colCommont+"</td>\r\n");
        		sbJsp.append("\t\t\t<td class=\"dialog-td-left\">\r\n");
        		sbJsp.append("\t\t\t\t<input type=\"text\" id=\"" + initCapLowBy2(colName) + "\" name=\"" + initCapLowBy2(colName) + "\" placeholder=\"请输入"+colCommont+"\" onkeyup=\"this.value=this.value.replace(/ /g,'')\"");
        		this.checkRequire(sbJsp, requireStr, colName);
        		this.checkLength(sbJsp, lengthStr, colName);
        		sbJsp.append("/>\r\n");
        		this.checkRequire2(sbJsp, requireStr, colName);
        		sbJsp.append("\t\t\t</td>\r\n");
        		sbJsp.append("\t\t</tr>\r\n");
        	}
        }
        sbJsp.append("\t</table>\r\n");
        sbJsp.append("\t<table class=\"dialog-two-table dialog-table-submit\">\r\n");
        sbJsp.append("\t\t<tr class=\"dialog-two-button\">\r\n");
        sbJsp.append("\t\t\t<td colspan=\"4\" >\r\n");
        sbJsp.append("\t\t\t\t<button type=\"button\" class=\"btn btn-warning submit-btn\">提 交</button>\r\n");
        sbJsp.append("\t\t\t\t&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\r\n");
        sbJsp.append("\t\t\t\t<button type=\"button\" class=\"btn btn-default cancel-btn\" target=\"_self\">返 回</button>\r\n");
        sbJsp.append("\t\t\t</td>\r\n");
        sbJsp.append("\t\t</tr>\r\n");
        sbJsp.append("\t</table>\r\n");
        sbJsp.append("</div>\r\n");
        sbJsp.append("</form>\r\n");
        sbJsp.append("<script type=\"text/javascript\">\r\n\r\n");
        sbJsp.append("\t//提交保存\r\n");
        sbJsp.append("\tfunction submitForm() {\r\n\r\n");
        sbJsp.append("\t\t$(\".submit-btn\").unbind(\"click\");\r\n");
        sbJsp.append("\t\t$('#submit_form').submit();\r\n\r\n");
        sbJsp.append("\t\treturn true;\r\n");
        sbJsp.append("\t}\r\n\r\n");
        sbJsp.append("\t//关闭窗口\r\n");
        sbJsp.append("\t$('.cancel-btn').click(function() {\r\n");
        sbJsp.append("\t\tart.dialog.close();\r\n");
        sbJsp.append("\t});\r\n\r\n");
        sbJsp.append("\t//下拉框初始化图形\r\n");
        sbJsp.append("\t$(\".chosen-select\").chosen({disable_search_threshold: 10});\r\n\r\n");
        sbJsp.append("</script>\r\n");
        sbJsp.append("</body>");
        
        // 生成jsp-new
 		try (FileWriter fw = new FileWriter(path + initSecCap(tableName) + "-new.jsp");
 			PrintWriter pw = new PrintWriter(fw)) {
         	pw.println(sbJsp.toString());
            pw.flush();
        } catch (Exception e) {
         	logger.error(e.getMessage());
        }
        
    	return sb;
    }
    
    /**
     * 生成修改功能
     * @param sb
     */
    private StringBuffer processUpdate(StringBuffer sb, String queryStr, String conditionStr, String lengthStr, String tableName, String tableComment, String requireStr, String insertStr, String updateStr, boolean ifDelete, String path, String ifKeyStr) {

    	// 修改方法
        sb.append("\t/**\r\n");
        sb.append("\t * 跳转修改页面\r\n");
        sb.append("\t */\r\n");
        sb.append("\t@RequestMapping(value = \"/edit\", method = RequestMethod.GET)\r\n");
        sb.append("\tpublic String edit(HttpServletRequest request, Model model, "+initcap(tableName)+" args) {\r\n\r\n");
        sb.append("\t// 获取修改的"+tableComment+"信息\r\n");
        sb.append("\tmodel.addAttribute(\"" + initSecCap(tableName) + "\", this." + initSecCap(tableName) + "Service.get(args));\r\n\r\n");
        sb.append("\t\treturn \"pages/" + initSecCap(tableName) + "/" + initSecCap(tableName) + "-edit\";\r\n");
        sb.append("\t}\r\n\r\n");
        
        sb.append("\t/**\r\n");
        sb.append("\t * 修改\r\n");
        sb.append("\t */\r\n");
        sb.append("\t@RequestMapping(value = \"/update\", method = RequestMethod.POST)\r\n");
        sb.append("\tpublic String update(HttpServletRequest request, " + initcap(tableName) + " args, RedirectAttributes attr) {\r\n\r\n");
        sb.append("\t\tlogger.info(\""+tableComment+"管理修改--开始！入参：{}\", JsonUtil.toJSON(args));\r\n\r\n");
        sb.append("\t\tint row = this." + initSecCap(tableName) + "Service.update(args);\r\n\r\n");
        sb.append("\t\tif (row >= 0) {\r\n");
        sb.append("\t\t\tlogger.info(\"修改"+tableComment+"--成功！出参：{}\", JsonUtil.toJSON(row));\r\n");
        sb.append("\t\t\tattr.addFlashAttribute(ERROR_TITLE, \""+tableComment+"修改成功！\");\r\n");
        sb.append("\t\t} else {\r\n");
        sb.append("\t\t\tlogger.info(\"修改"+tableComment+"--失败！出参：{}\", JsonUtil.toJSON(row));\r\n");
        sb.append("\t\t\tattr.addFlashAttribute(ERROR_TITLE, \""+tableComment+"修改失败！\");\r\n");
        sb.append("\t\t}\r\n");
        sb.append("\t\treturn REDIRECT_LIST;\r\n");
        sb.append("\t}\r\n\r\n");
        if (ifDelete == false) {
        	sb.append("}\r\n");
        }
    	
    	// 生成JSP-edit
        StringBuffer sbJsp = new StringBuffer();
        sbJsp.append("<%@ page language=\"java\" contentType=\"text/html; charset=utf-8\" pageEncoding=\"utf-8\"%>\r\n");
        sbJsp.append("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%>\r\n");
        sbJsp.append("<%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jsp/jstl/fmt\"%>\r\n");
        sbJsp.append("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %>\r\n");
        sbJsp.append("<jsp:include page=\"../common/file.jsp\" />\r\n");
        sbJsp.append("<head>\r\n");
        sbJsp.append("</head>\r\n");
        sbJsp.append("<body class=\"dialog_body\">\r\n");
        sbJsp.append("<form id=\"submit_form\" action=\"${pageContext.request.contextPath}/" + initSecCap(tableName) + "/update\" method=\"post\" target=\"_parent\">\r\n");
        sbJsp.append("<input type=\"hidden\" id=\""+initSecCapLow(ifKeyStr)+"\" name=\""+initSecCapLow(ifKeyStr)+"\" value=\"${" + initSecCap(tableName) + "."+initSecCapLow(ifKeyStr)+" }\"/>\r\n");
        sbJsp.append("<div class=\"dialog-two-div\">\r\n");
        sbJsp.append("\t<table class=\"dialog-two-table\">\r\n");
        
        String updateStrArr[] = null;
        if (!StringUtils.isEmpty(updateStr.trim())) {
        	
        	updateStrArr = updateStr.trim().split("@");
        	
        	for (int i=0; i<updateStrArr.length; i++) {
        		String arr[] = updateStrArr[i].split("#");
        		String colName = arr[0];
        		String colCommont = arr[1];
        		
        		sbJsp.append("\t\t<tr>\r\n");
        		sbJsp.append("\t\t\t<td class=\"dialog-td-right\">"+colCommont+"</td>\r\n");
        		sbJsp.append("\t\t\t<td class=\"dialog-td-left\">\r\n");
        		sbJsp.append("\t\t\t\t<input type=\"text\" id=\"" + initCapLowBy2(colName) + "\" name=\"" + initCapLowBy2(colName) + "\" value=\"${" + initSecCap(tableName) + "." + initCapLowBy2(colName) + " }\" placeholder=\"请输入"+colCommont+"\" onkeyup=\"this.value=this.value.replace(/ /g,'')\"");
        		this.checkRequire(sbJsp, requireStr, colName);
        		this.checkLength(sbJsp, lengthStr, colName);
        		sbJsp.append("/>\r\n");
        		this.checkRequire2(sbJsp, requireStr, colName);
        		sbJsp.append("\t\t\t</td>\r\n");
        		sbJsp.append("\t\t</tr>\r\n");
        	}
        }
        sbJsp.append("\t</table>\r\n");
        sbJsp.append("\t<table class=\"dialog-two-table dialog-table-submit\">\r\n");
        sbJsp.append("\t\t<tr class=\"dialog-two-button\">\r\n");
        sbJsp.append("\t\t\t<td colspan=\"4\" >\r\n");
        sbJsp.append("\t\t\t\t<button type=\"button\" class=\"btn btn-warning submit-btn\">提 交</button>\r\n");
        sbJsp.append("\t\t\t\t&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\r\n");
        sbJsp.append("\t\t\t\t<button type=\"button\" class=\"btn btn-default cancel-btn\" target=\"_self\">返 回</button>\r\n");
        sbJsp.append("\t\t\t</td>\r\n");
        sbJsp.append("\t\t</tr>\r\n");
        sbJsp.append("\t</table>\r\n");
        sbJsp.append("</div>\r\n");
        sbJsp.append("</form>\r\n");
        sbJsp.append("<script type=\"text/javascript\">\r\n\r\n");
        sbJsp.append("\t//提交保存\r\n");
        sbJsp.append("\tfunction submitForm() {\r\n\r\n");
        sbJsp.append("\t\t$(\".submit-btn\").unbind(\"click\");\r\n");
        sbJsp.append("\t\t$('#submit_form').submit();\r\n\r\n");
        sbJsp.append("\t\treturn true;\r\n");
        sbJsp.append("\t}\r\n\r\n");
        sbJsp.append("\t//关闭窗口\r\n");
        sbJsp.append("\t$('.cancel-btn').click(function() {\r\n");
        sbJsp.append("\t\tart.dialog.close();\r\n");
        sbJsp.append("\t});\r\n\r\n");
        sbJsp.append("\t//下拉框初始化图形\r\n");
        sbJsp.append("\t$(\".chosen-select\").chosen({disable_search_threshold: 10});\r\n\r\n");
        sbJsp.append("</script>\r\n");
        sbJsp.append("</body>");
        
        // 生成jsp-edit
 		try (FileWriter fw = new FileWriter(path + initSecCap(tableName) + "-edit.jsp");
 			PrintWriter pw = new PrintWriter(fw)) {
         	pw.println(sbJsp.toString());
            pw.flush();
        } catch (Exception e) {
         	logger.error(e.getMessage());
        }
        
    	return sb;
    }
    
    /**
     * 生成删除功能
     * @param sb
     */
    private StringBuffer processDelete(StringBuffer sb, String queryStr, String conditionStr, String lengthStr, String tableName, String tableComment, String requireStr, String insertStr, String updateStr, boolean ifDelete, String path, String ifKeyStr) {

    	// 删除方法
        sb.append("\t/**\r\n");
        sb.append("\t * 删除\r\n");
        sb.append("\t */\r\n");
        sb.append("\t@RequestMapping(value = \"/delete\", method = RequestMethod.POST)\r\n");
        sb.append("\tpublic void delete(HttpServletRequest request, HttpServletResponse response, "+initcap(tableName)+" args) {\r\n\r\n");
        sb.append("\t\tlogger.info(\""+tableComment+"管理删除--开始！入参：{}\", JsonUtil.toJSON(args));\r\n\r\n");
        sb.append("\t\tJSONResult result = new JSONResult();\r\n\r\n");
        
        
        sb.append("\t\tint row = this." + initSecCap(tableName) + "Service.delete(args);\r\n\r\n");
        sb.append("\t\tif (row >= 0) {\r\n");
        sb.append("\t\t\tresult.setMessage(\"删除成功！\");\r\n");
        sb.append("\t\t\tgetPrintWriter(response,JSONArray.toJSONString(result));\r\n");
        sb.append("\t\t\tlogger.info(\""+tableComment+"管理删除--成功，出参：{}\", JsonUtil.toJSON(result));\r\n");
        sb.append("\t\t} else {\r\n");
        sb.append("\t\t\tresult.setMessage(\"删除失败！\");\r\n");
        sb.append("\t\t\tgetPrintWriter(response,JSONArray.toJSONString(result));\r\n");
        sb.append("\t\t\tlogger.info(\""+tableComment+"管理删除--失败，出参：{}\", JsonUtil.toJSON(result));\r\n");
        sb.append("\t\t}\r\n");
        sb.append("\t}\r\n\r\n");
        sb.append("}\r\n");
    	
    	return sb;
    }
  
    /**
     * 是否必填判断
     * @param sb
     * @return
     */
    private StringBuffer checkRequire(StringBuffer sb, String requireStr, String colNameS) {
    	
    	if (!StringUtils.isEmpty(requireStr.trim())) {
    		
    		String requireStrArr[] = requireStr.trim().split("@");
    		
        	for (int i=0; i<requireStrArr.length; i++) {
        		String arr[] = requireStrArr[i].split("#");
        		String colName = arr[0];
        		
        		if (!StringUtils.isEmpty(colName) && colNameS.equals(colName)) {
        			sb.append(" validate=\"not-null\" ");
        		}
        	}
        }
    	return sb;
    }
    
    /**
     * 是否必填判断(加*号)
     * @param sb
     * @return
     */
    private StringBuffer checkRequire2(StringBuffer sb, String requireStr, String colNameS) {
    	
    	if (!StringUtils.isEmpty(requireStr.trim())) {
    		
    		String requireStrArr[] = requireStr.trim().split("@");
    		
        	for (int i=0; i<requireStrArr.length; i++) {
        		String arr[] = requireStrArr[i].split("#");
        		String colName = arr[0];
        		
        		if (!StringUtils.isEmpty(colName) && colNameS.equals(colName)) {
        			sb.append("\t\t\t\t<span class=\"redtext\">*</span>\r\n");
        		}
        	}
        }
    	return sb;
    }
    
    /**
     * 长度限制
     * @param sb
     * @return
     */
    private StringBuffer checkLength(StringBuffer sb, String lengthStr, String colNameS) {
    	
    	if (!StringUtils.isEmpty(lengthStr.trim())) {
    		
    		String lengthStrArr[] = lengthStr.trim().split("@");
    		
        	for (int i=0; i<lengthStrArr.length; i++) {
        		String arr[] = lengthStrArr[i].split("#");
        		String colName = arr[0];
        		String length = arr[1];
        		
        		if (!StringUtils.isEmpty(colName) && colNameS.equals(colName)) {
        			sb.append(" maxlength=\""+length+"\" ");
        		}
        	}
        }
    	
    	return sb;
    }
}